/*
 * main.cpp
 */

#include <wx/wx.h> 

#include <boost/filesystem.hpp>
#include <boost/foreach.hpp>
#include <boost/regex.hpp>

#include "ttcodeStateChart.h"
#include "ttcodeMainFrame.h"

#include "comLogManager.h"
setLogFile("./ttcode.log",ios_base::app);

#ifndef WIN32
#include <gtk/gtk.h>
#endif

class MainApp: public wxApp
{
    virtual bool OnInit();
	virtual int OnExit();
private:
	void loadEnv(void);

private:
	string m_tt_res_home;
	string m_doc_name;
};

IMPLEMENT_APP(MainApp)

bool MainApp::OnInit()
{
#ifndef WIN32
	char **argv_ = (char **)argv;
	int argc_ = argc;
	gtk_init(&argc_, &argv_);;
#endif
	wxInitAllImageHandlers();

	ttcode_log << "<" << argv[0] << ">start" << endl;
	this->loadEnv();
	globalStateChart.initiate();

	globalFrame = new MainFrameMgr(NULL);
	globalStateChart.process_event( eventInitWidgets() );
	if( m_doc_name.empty() )
	{
		globalStateChart.process_event( eventEmpty() );
	}
	else
	{
		ttcode_log << "m_doc_name=<" << m_doc_name << ">" << endl;
		globalStateChart.process_event( eventLoadProject() );
	}
    globalFrame->Show(true);
    this->SetTopWindow(globalFrame);
    return true;
}
void MainApp::loadEnv(void)
{
	using namespace boost;
	using namespace boost::filesystem;
	
	path exec_path(argv[0]);
	path tmp;
	tmp = exec_path.parent_path();
	tmp = tmp.parent_path();
	string tt_home = tmp.parent_path().string();

	globalTTEnv["tt_home"] = tt_home;

	m_tt_res_home = tt_home + "/tt-app/Resource";
	ttcode_log << "tt_home=<" << tt_home << ">end" << endl;

	globalTTEnv["res_home"] = m_tt_res_home;
	globalTTEnv["pwd"] = current_path().string();

	boost::regex rex("\\.ttcode$");
	boost::smatch what;
	for( int i = 0 ; i < argc ; i++ )
	{
		string docName(argv[i]);
		if( boost::regex_search(docName,what, rex) )
		{
			m_doc_name = docName;
			break;
		}
	}
	if( !m_doc_name.empty() )
	{
		path doc_path(m_doc_name);
		globalTTEnv["doc_name"] = m_doc_name;
		globalTTEnv["doc_home"] = doc_path.parent_path().string();
	}
}

int MainApp::OnExit()
{
	ttcode_log << "<" << argv[0] << ">end" << endl;
	globalStateChart.process_event( eventCloseAll() );
	return 0;
}
